package com.my.study.globalfilter.normal;

import com.my.study.aop.annotation.FilterType;
import com.my.study.entity.vo.UserInfoVO;
import com.my.study.enums.ApiTypeEnum;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.util.HttpGlobalUtil;
import com.my.study.utils.JwtUtil;
import com.my.study.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class UserInfoFilter implements GlobalFilter, Ordered {

    @FilterType(type = ApiTypeEnum.NORMAL_API)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpRequest request = exchange.getRequest();
            String token = request.getHeaders().getFirst("Authorization");
            // 将数据保存到redis
            UserInfoVO userInfo = JwtUtil.getUserInfo(token);
            RedisUtil.setString(userInfo.getUserId(), userInfo);
            // 添加账号到头部
            request.mutate().headers(httpHeaders -> httpHeaders.add("userId", userInfo.getUserId()));
        } catch (Exception exception) {
            return HttpGlobalUtil.fail(exchange.getResponse(), BusinessExceptionEnum.SYSTEM_ERROR.code);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
